/**
 *    Copyright (C) 2008, 2009  Victor Smirnov <aist11@gmail.com>
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License along
 *    with this program; if not, write to the Free Software Foundation, Inc.,
 *    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 *    See LICENSE.exceptions in the root folder of this project for possible
 *    exceptions
 *
 */

package ru.teleology.cubefs.editor.hex;

public class HexHelper {
	
	public static long idiv(long arg, long val) {
		return arg / val + (arg % val == 0 ? 0 : 1);
	}
	
	public static String asHex(long value, int digits) {
		StringBuilder sb = new StringBuilder();
		
		for (int c = 0; c < digits; c++) {
			int v = (int) ((value >> c * 4) & 0xF);
			switch (v) {
				case 0: sb.append('0'); break;
				case 1: sb.append('1'); break;
				case 2: sb.append('2'); break;
				case 3: sb.append('3'); break;
				case 4: sb.append('4'); break;
				case 5: sb.append('5'); break;
				case 6: sb.append('6'); break;
				case 7: sb.append('7'); break;
				case 8: sb.append('8'); break;
				case 9: sb.append('9'); break;
				case 10: sb.append('A'); break;
				case 11: sb.append('B'); break;
				case 12: sb.append('C'); break;
				case 13: sb.append('D'); break;
				case 14: sb.append('E'); break;
				case 15: sb.append('F'); break;
			}
		}
		
		return sb.reverse().toString();
	}

	public static int toInt(String value) {
		int val = 0;
		
		for (int c = 0; c < value.length(); c++) {
			int v = 0;
			switch (value.charAt(value.length() - c - 1)) {
			case '0': v = 0; break;
			case '1': v = 1; break;
			case '2': v = 2; break;
			case '3': v = 3; break;
			case '4': v = 4; break;
			case '5': v = 5; break;
			case '6': v = 6; break;
			case '7': v = 7; break;
			case '8': v = 8; break;
			case '9': v = 9; break;
			case 'a': v = 10; break;
			case 'A': v = 10; break;
			case 'b': v = 11; break;
			case 'B': v = 11; break;
			case 'c': v = 12; break;
			case 'C': v = 12; break;
			case 'd': v = 13; break;
			case 'D': v = 13; break;
			case 'e': v = 14; break;
			case 'E': v = 14; break;
			case 'f': v = 15; break;
			case 'F': v = 15; break;
			}
			
			val =  val | (v << (c*4));
		}
		
		return val;
	}	
}
